package org.example.interceptor;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.CurrentHolder;
import org.example.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
/**
 * 定义拦截器
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //获取请求路径
//        String requestURI = request.getRequestURI();
//        log.info("拦截器拦截请求:{}", requestURI);
//        //判断是否是登录请求
//        if (requestURI.contains("/login")) {
//            log.info("登录操作，放行");
//            return true;}
            //获取请求头中的令牌（token）
            String jwt = request.getHeader("token");

            log.info("获取请求头中的令牌:{}", jwt);

            //判断令牌是否存在，如果不存在，返回401
            if (jwt == null|| jwt.isEmpty()) {
                log.info("请求头中无token,返回401");
                response.setStatus(401);
                return false;
            }
            //如果存在，就进行解析，解析成功返回true，解析失败返回false
            try {
                JwtUtils.parseToken(jwt);
                Claims claimas = JwtUtils.parseToken(jwt);
                CurrentHolder.setCurrentId(Integer.parseInt(claimas.get("id").toString()));//设置当前线程绑定的id
                log.info("令牌解析成功,当前登陆ID:"+claimas.get("id"));
                return true;
            } catch (Exception e) {
                log.info("解析失败");
                response.setStatus(401);
                return false;
            }
        }
        public void PostHandle(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

                //释放资源
                CurrentHolder.remove();
            }

    }
